package com.dbs.zstp.common.controller;

import com.alibaba.fastjson.JSON;
import com.dbs.zstp.common.model.Result;
import com.dbs.zstp.common.service.BaseService;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



/**
 * 公共抽象控制层
 * @param <T>
 */
@SuppressWarnings("unchecked")
public abstract class BaseController<T> {

    private ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<HttpServletRequest>();
    private ThreadLocal<HttpServletResponse> responseThreadLocal = new ThreadLocal<HttpServletResponse>();
    private ThreadLocal<HttpSession> sessionThreadLocal = new ThreadLocal<HttpSession>();
    private ThreadLocal<ServletContext> contextThreadLocal = new ThreadLocal<ServletContext>();

    @SuppressWarnings("rawtypes")
	public abstract BaseService getService();

    /**
     * 初始化controller
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        //注册时间格式转换器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    /**
     * 访问请求时资源初始化
     * @param request
     * @param response
     */
    @ModelAttribute
    public void setAttribute(HttpServletRequest request,HttpServletResponse response){
        requestThreadLocal.set(request);
        responseThreadLocal.set(response);
        sessionThreadLocal.set(request.getSession());
        contextThreadLocal.set(request.getServletContext());
    };


    /**
     * 单条数据查询，例：
     * type:'get'
     * url:'api/sysUser/{id:1,name:"张三"}'
     * data:null
     *
     * @param t
     * @return
     */
    @RequestMapping(value = "/row", method = RequestMethod.GET)
    @ResponseBody
    public Object row(T t) {
        try {
            return getService().selectOne(t);
        } catch (Exception e) {
            catchException(e);
            return null;
        }
    }

    /**
     * 单条数据新增，例：
     * type:'post'
     * url:'api/sysUser'（数据为form表单数据，或ajax请求的data参数）
     * data:{id:1,name:"张三"} //（或数据为form表单数据）
     *
     * @param t
     * @return
     */
	@RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Object add(T t) {
        try {
            return getService().insertSelective(t);
        } catch (Exception e) {
            catchException(e);
            return error(e);
        }
    }

    /**
     * 单条数据修改，例：
     * type:'put'
     * url:'api/sysUser'
     * data:{id:1,name:'张三'}
     *
     * @param t
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public Object update(T t) {
        try {
            getService().updateByPrimaryKeySelective(t);
            return success();
        } catch (Exception e) {
            catchException(e);
            return error(e);
        }
    }

    /**
     * 数据删除，例：
     * type:'delete'
     * url:'api/sysUser/1' //方式一，条件为单主键
     * url:'api/sysUser/1,2,3' //方式二，条件为主键集合
     * url:'api/sysUser/[1,2,3]' //方式三，条件为主键集合
     * url:'api/sysUser/{id:"1",name:"张三"}' //方式四，条件为实体对象
     * url:'api/sysUser/[{id:"1",name:"张三"},{id:"2",name:"李四"}]' //方式五，条件为实体集合
     * data:null
     *
     * @param keys
     * @param t
     * @return
     */
    @RequestMapping(value = "/{keys}", method = RequestMethod.DELETE)
    @ResponseBody
    public Object delete(@PathVariable String keys, T t) {
        if(StringUtils.isBlank(keys)){
            return error("参数获取失败!");
        }

        try {
            if(keys.startsWith("[{")){ // 实体集合，例：[{id:'1',name:'张三'},{id:'2',name:'李四'}]
                getService().delete(JSON.parseArray(keys, t.getClass()));
            }
            return success();
        } catch (Exception e) {
            catchException(e);
            return error(e);
        }
    }


    /**
     * 列表查询，例
     * type:'get'
     * url:'api/sysUsers/list'
     * data:{
     *      name:"张", age:26, // 搜索内容
     * }
     *
     * @param t
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<T> list(T t) {
        try {
            return getService().select(t);
        } catch (Exception e) {
            catchException(e);
            return null;
        }
    }

    public void catchException(Exception e) {
        if (null != e.getCause()) {
//            logger.error(e.getCausetCause().getMessage(), e.getCause());
        }else {
//            logger.error(error.getMessage(), e);
        }
    }

    public Result success() {
        return new Result(true);
    }

    public Result success(String msg) {
        return new Result(true, msg);
    }

    public Result error(String msg) {
        return new Result(false, msg);
    }

    public Result error(Exception e) {
        return new Result(false, null != e.getCause() ? e.getCause().getMessage() : e.getMessage());
    }
    public HttpServletRequest getRequest() {
        return requestThreadLocal.get();
    }

    public HttpServletResponse getResponse() {
        return responseThreadLocal.get();
    }

    public HttpSession getSession() {
        return sessionThreadLocal.get();
    }

    public ServletContext getContext() {
        return contextThreadLocal.get();
    }
    
    
    
   
}
